package com.ruicar.afs.cloud.afscase.component;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruicar.afs.cloud.afscase.apply.service.PrintManageService;
import com.ruicar.afs.cloud.bizcommon.print.entity.ComPrintFormManage;
import com.ruicar.afs.cloud.bizcommon.print.service.ComPrintFormManageService;
import com.ruicar.afs.cloud.common.core.enums.AfsEnumUtil;
import com.ruicar.afs.cloud.common.core.service.ServiceInfo;
import com.ruicar.afs.cloud.common.core.util.SpringContextHolder;
import com.ruicar.afs.cloud.common.data.lock.anno.Lock;
import com.ruicar.afs.cloud.image.enums.IsEnableRuleEnum;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

@Component
@Slf4j
@AllArgsConstructor
public class PrintEffectiveOrInvalidByDatePublishComponent implements ApplicationListener<ApplicationReadyEvent> {
    private static final ScheduledExecutorService EXECUTOR_SERVICE = Executors.newSingleThreadScheduledExecutor();
    private final PrintManageService printManageService;
    private final ComPrintFormManageService comPrintFormManageService;
    @Override
    public void onApplicationEvent(ApplicationReadyEvent event) {
        schedule();
    }

    @Lock(keyConstant = ":lock-afs-print-effective-invalid-publish", keys = {"#serviceName"})
    public void publishVouchers(String serviceName) {
        try {
            log.debug("打印模板数据同步--start");
            //打印模板 生效启用的到了失效时间 把状态改为未启用
            IPage iPage = comPrintFormManageService.page(new Page<>(1, 100),
                    Wrappers.<ComPrintFormManage>lambdaQuery().eq(ComPrintFormManage::getIsEnable, AfsEnumUtil.key(IsEnableRuleEnum.YES)).lt(ComPrintFormManage::getFailureTime, new Date()));
            List<ComPrintFormManage> list =iPage.getRecords();
            for(ComPrintFormManage comPrintFormManage :list){
                comPrintFormManage.setIsEnable(AfsEnumUtil.key(IsEnableRuleEnum.NO));
                ProcessingData(comPrintFormManage);
            }
            //打印模板  未启用的到了生效时间 把状态改为启用
            iPage = comPrintFormManageService.page(new Page<>(1, 100),
                    Wrappers.<ComPrintFormManage>lambdaQuery().eq(ComPrintFormManage::getIsEnable, AfsEnumUtil.key(IsEnableRuleEnum.NO)).gt(ComPrintFormManage::getEffectTime, new Date()));
            list =iPage.getRecords();
            for(ComPrintFormManage comPrintFormManage :list){
                comPrintFormManage.setIsEnable(AfsEnumUtil.key(IsEnableRuleEnum.YES));
                ProcessingData(comPrintFormManage);
            }
            log.debug("打印模板数据同步--end");
        } catch (Throwable e) {
            log.error("打印模板数据同步失败", e);
        }
    }
    //处理数据
    @Transactional(rollbackFor = Exception.class)
    public void ProcessingData(ComPrintFormManage  comPrintFormManage){
        comPrintFormManageService.saveOrUpdate(comPrintFormManage);
        printManageService.submitPrintFormManage(comPrintFormManage);
    }
    private void schedule() {
        //每10s 检测发布处理一次打印模板信息
        EXECUTOR_SERVICE.scheduleWithFixedDelay(() -> {
            SpringContextHolder.getBean(PrintEffectiveOrInvalidByDatePublishComponent.class).publishVouchers(ServiceInfo.getServiceName());
        }, 2, 10, TimeUnit.SECONDS);

    }
}
